// 返回统一的回调处理器

function toast(sms, icon = 'none', fun, t = 1500) {
  console.log('[toast]', sms);
  if ((typeof sms) == 'object') {
    try {
      sms = JSON.stringify(sms);
    } catch (err) {}
  }
  wx.showToast({
    title: sms,
    icon: icon,
    duration: t,
    success: fun
  })
}

function t(sms, type = 0, t = 2500, fun) {
  console.log('[toast]', sms);
  if ((typeof sms) == 'object') {
    try {
      sms = JSON.stringify(sms);
    } catch (err) {}
  }
  var icon = 'none';
  var image = '';
  if (type == 1) // suc
    image = '../../images/m/icon_sucess.png';
  wx.showToast({
    image,
    title: sms,
    icon,
    duration: t,
    success: fun
  })
}

function askRefresh(code, data, cb1, cb2, t = '提示') {
  var hint = '获取信息失败：' + data + '(' + code + ')。是否重试?';
  if (code == 1101) {
    if (data.errMsg.indexOf("request:fail") > -1)
      hint = "网络无法连接，请检查网络后重试"
    else
      hint = '获取信息失败：' + data.errMsg + '。是否重试?';
  } else if (code == 1200) {
    hint = '获取信息失败：尚未登录。是否重试?';
  }
  console.log('[askRefresh]' + hint);
  wx.showModal({
    title: '' + t,
    content: hint,
    cancelColor: '#666',
    confirmColor: '#FF259F',
    success: function(res) {
      if (res.confirm) {
        if (cb1)
          cb1();
      } else if (res.cancel) {
        if (cb2)
          cb2();
      }
    }
  });
}

function showRefresh(cb1, cb2, c = '请求超时，点击确定刷新重试', t = '提示') {
  wx.showModal({
    title: t + '',
    content: '' + c,
    cancelColor: '#999',
    confirmColor: '#FF259F',
    success: function(res) {
      if (res.confirm) {
        if (cb1)
          cb1();
      } else if (res.cancel) {
        if (cb2)
          cb2();
      }
    }
  })
  console.log('[showRefresh]', c);
}

function showModal(c, t = '提示', fun, tSuc = '确定') {
  if ((typeof c) == 'object') {
    try {
      c = JSON.stringify(c);
    } catch (err) {}
  }
  wx.showModal({
    title: "" + t,
    content: c,
    showCancel: false,
    success: fun,
    confirmText: tSuc,
    cancelColor: '#999',
    confirmColor: '#E1B861'
  })
  console.log('[showModal]', c);
}

function showDialog(c, cancelText, cancelCb, confirmText, confirmCb, t = '提示') {
  if ((typeof c) == 'object') {
    try {
      c = JSON.stringify(c);
    } catch (err) {}
  }
  wx.showModal({
    title: t + '',
    content: c,
    showCancel: true,
    cancelText: cancelText,
    confirmText,
    confirmText,
    cancelColor: '#999',
    confirmColor: '#FF5679',
    success: function(res) {
      if (res.confirm) {
        confirmCb && (typeof confirmCb == 'function') && confirmCb()
      } else if (res.cancel) {
        cancelCb && (typeof cancelCb == 'function') && cancelCb()
      }
    }
  });
  console.log('[showDialog]', c);
}

function showLoading(t = '正在加载中') {
  try {
    wx.showLoading({
      title: t
    });
  } catch (e) {
    l(e.toString());
    toast(t);
  }
}

function hideLoading() {
  try {
    wx.hideLoading()
  } catch (e) {}
}


function l(name, j) {
  var s = name;
  if (j) {
    try {
      s += (" : " + JSON.stringify(j));
    } catch (e) {
      console.log("json.stringify 失败");
      s += j;
    }
  }
  console.log(s);
}

function getFileNameByPath(path) {
  var newDateStr = new Date().toLocaleDateString();
  var extension = /\.([^.]*)$/.exec(path);
  if (extension) {
    extension = extension[1].toLowerCase();
  }
  var name = newDateStr + "." + extension; //上传的图片的别名
  return name;
}

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  var len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (var i = 0; i < len; i++) {
    var num1 = parseInt(v1[i])
    var num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
}

function share() {
  var t = '智能训练营',
    p = '/pages/index/index';
  return {
    title: t,
    path: p,
    imageUrl: '../../images/img_scenes.png'
  }
}

module.exports.getWeekDay = (myDate) => {
  var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  return weekDay[myDate.getDay()]
}

// yyyy年MM月dd日hh小时mm分ss秒
function format(date, format) {
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length))
    }
  }
  return format;
}

function formatTime(date, isShort, s = '-') {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  var res = [year, month, day].map(formatNumber).join(s);
  if (!isShort)
    res += (' ' + [hour, minute, second].map(formatNumber).join(':'));
  return res;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getTimeStr(n) {
  return n > 9 ? n : '0' + n
}

function getShowTime(t) {
  var h = parseInt(t / 3600),
    m = parseInt(t / 60) % 60,
    s = t % 60;
  h = (h > 0 ? (getTimeStr(h) + ':') : '');
  return (h + getTimeStr(m) + ':' + getTimeStr(s));
}

function parseTime(str) {
  if (typeof(str) != 'number')
    str = replaceAll(str, '-', '/');
  return new Date(str);
}

function replaceAll(w, s1, s2) {
  if(!w)
    return w;
  return w.replace(new RegExp(s1, 'gm'), s2);
}

function sort(arr) {
  var len = arr.length;
  for (var i = 0; i < len; i++) {
    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) { // 相邻元素两两对比
        var temp = arr[j + 1]; // 元素交换
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

function isInArray(arr, value) {
  if (!arr)
    return false;
  for (var i = 0, l = arr.length; i < l; i++) {
    if (value === arr[i]) {
      return true;
    }
  }
  return false;
}


module.exports.dealDetail = function (detail) {
  if (!detail) detail = ''
  return detail.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block" ')
}

module.exports.backLater = function () {
  setTimeout(function () {
    wx.navigateBack({})
  }, 1600)
}

module.exports.encode = function (data) {
  try {
    return encodeURIComponent(JSON.stringify(data))
  } catch (e) {
    console.log(e)
    return ''
  }
}

module.exports.decode = function (data) {
  try {
    return JSON.parse(decodeURIComponent(data))
  } catch (e) {
    console.log(e)
    return {}
  }
}

module.exports.decode = function(data) {
  try {
    return JSON.parse(decodeURIComponent(data))
  } catch (e) {
    console.log(e)
    return {}
  }
}

module.exports.toast = toast;
module.exports.t = t;
module.exports.showModal = showModal;
module.exports.showDialog = showDialog;
module.exports.askRefresh = askRefresh;
module.exports.showRefresh = showRefresh;
module.exports.showLoading = showLoading;
module.exports.hideLoading = hideLoading;
module.exports.l = l;
module.exports.getFileNameByPath = getFileNameByPath;
module.exports.share = share;
module.exports.format = format;
module.exports.formatTime = formatTime;
module.exports.parseTime = parseTime;
module.exports.compareVersion = compareVersion;
module.exports.getShowTime = getShowTime;
module.exports.sort = sort;
module.exports.isInArray = isInArray;
module.exports.replaceAll = replaceAll;